<script setup>
import { ref, onMounted } from "vue"

onMounted(() => {
	canvas_init()
	// 监听音频元素
	audioEL.value.onplaying = () => {
		// if(isInit) return
		audio_init()
		console.log("audioEL.value.onplay1")
		isInit.value = true
	}
})

const Cvs = ref(null)
const Ctx = ref(null)
const audioEL = ref(null)
const isInit = ref(false)
const analyser = ref(null)
const Arr = ref([])

// 初始化画布并获取画笔
const canvas_init = () => {
	const div = document.querySelector(".container")
	Ctx.value = Cvs.value.getContext("2d")
	Cvs.value.width = div.clientWidth * devicePixelRatio
	Cvs.value.height = (div.clientHeight / 1.5) * devicePixelRatio
}

// 音频初始化
const audio_init = () => {
	// 创建音频上下文
	const audioCtx = new AudioContext()
	// 创建音频节点
	const audioSrc = audioCtx.createMediaElementSource(audioEL.value)
	// 创建音频分析器
	analyser.value = audioCtx.createAnalyser()
	// 设置音频宽度
	analyser.value.fftSize = 512
	// 创建数组
	Arr.value = new Uint8Array(analyser.value.frequencyBinCount)
	// 音频节点连接到分析器
	audioSrc.connect(analyser.value)
	// 将音频分析器连接到音频上下文
	analyser.value.connect(audioCtx.destination)
	cvs_draw()
}

const cvs_draw = () => {
	requestAnimationFrame(cvs_draw)
	// 清空画布
	Ctx.value.clearRect(0, 0, Cvs.value.width, Cvs.value.height)
	if(!isInit) return
	analyser.value.getByteFrequencyData(Arr.value)
	const len = Arr.value.length
	const barWidth = Cvs.value.width / len / 2
	for(let i=0; i<len; i++) {
		const data = Arr.value[i]
		const barHeight = Cvs.value.height * data / 255
		const x1 = i * barWidth + Cvs.value.width  / 2
		const x2 = Cvs.value.width  / 2 - (i + 1) * barWidth
		const y = Cvs.value.height - barHeight
		Ctx.value.fillStyle = "rgba(255,255,255,0.8)"
		Ctx.value.fillRect(x1, y, barWidth - 2, barHeight)
		Ctx.value.fillRect(x2, y, barWidth - 2, barHeight)

	}
}
</script>

<template>
	<div class="container">
		<canvas ref="Cvs"></canvas>
		<audio controls ref="audioEL">
			<source
				src="@/assets/audio/01.ogg"
				type="audio/ogg"
			/>
		</audio>
	</div>
</template>

<style scoped lang="scss">
.container {
	flex: 1;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	canvas {
		border: 1px solid $all-border-color;
	}
	audio {
		margin-top: 40px;
		source {
		}
	}
}
</style>
